package com.soFun.service;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

/**
 * AI服务，提供LangChain4j相关功能
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AiService {

    private final ChatLanguageModel chatLanguageModel;

    /**
     * 与AI进行简单对话
     * @param userMessage 用户消息内容
     * @return AI回复内容
     */
    public String chat(String userMessage) {
        log.info("处理聊天请求: {}", userMessage);
        try {
            UserMessage message = UserMessage.from(userMessage);
            AiMessage response = invokeGenerateMethod(message);
            String result = response.text();
            log.info("聊天响应完成，响应长度: {}", result.length());
            return result;
        } catch (Exception e) {
            log.error("聊天处理失败: {}", e.getMessage(), e);
            throw new RuntimeException("聊天处理失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 生成文本摘要
     * @param text 需要摘要的文本
     * @return 生成的摘要
     */
    public String generateSummary(String text) {
        log.info("处理文本摘要请求，文本长度: {}", text.length());
        try {
            String prompt = "请为以下文本生成一个简洁的摘要：\n\n" + text;
            UserMessage message = UserMessage.from(prompt);
            AiMessage response = invokeGenerateMethod(message);            String result = response.text();
            log.info("摘要生成完成，摘要长度: {}", result.length());
            return result;
        } catch (Exception e) {
            log.error("摘要生成失败: {}", e.getMessage(), e);
            throw new RuntimeException("摘要生成失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 翻译文本到指定语言
     * @param text 原文本
     * @param targetLanguage 目标语言
     * @return 翻译后的文本
     */
    public String translate(String text, String targetLanguage) {
        log.info("处理翻译请求，原文长度: {}, 目标语言: {}", text.length(), targetLanguage);
        try {
            String prompt = String.format("请将以下文本翻译成%s：\n\n%s", targetLanguage, text);
            UserMessage message = UserMessage.from(prompt);
            AiMessage response = invokeGenerateMethod(message);            String result = response.text();
            log.info("翻译完成，结果长度: {}", result.length());
            return result;
        } catch (Exception e) {
            log.error("翻译处理失败: {}", e.getMessage(), e);
            throw new RuntimeException("翻译处理失败: " + e.getMessage(), e);
        }
    }

    private AiMessage invokeGenerateMethod(UserMessage message) throws Exception {
        Method generateMethod = chatLanguageModel.getClass().getMethod("generate", UserMessage.class);
        return (AiMessage) generateMethod.invoke(chatLanguageModel, message);
    }
} 